<template>
    <view class="dishes-container">
      <!-- 顶部导航 -->
      <view class="header">
        <view class="header-content">
          <view class="back-btn" @click="goBack">
            <text class="back-text">返回</text>
          </view>
          <view class="title">
            <text class="title-text">确认收货</text>
          </view>
          <view style="display: flex;align-items: center">
<!--          <view class="save-btn" @click="save(false)" style="margin-right: 32rpx">-->
<!--            <text class="save-text">保存</text>-->
<!--          </view>-->
          <view class="save-btn" @click="submit(true)">
            <text class="save-text" style="color: green">提交</text>
          </view>
        </view>
        </view>
      </view>

      <!-- 搜索栏 -->
      <view class="search-section">
        <view class="search-box">
          <image src="/static/image/icon_search.png" class="search-icon" mode="aspectFit"></image>
          <input
            type="text"
            v-model="searchKeyword"
            placeholder="搜索菜品名称"
            class="search-input"
            @input="onSearchInput"
          />
        </view>
      </view>

      <!-- 菜品列表 -->
      <scroll-view class="dish-list" scroll-y="true">
        <!-- 加载状态 -->
        <view v-if="loading" class="loading-state">
          <text class="loading-text">加载中...</text>
        </view>

        <!-- 空状态 -->
        <view v-else-if="filteredDishList.length === 0" class="empty-state">
          <image src="/static/image/no_permission.png" class="empty-icon" mode="aspectFit"></image>
          <text class="empty-text">暂无菜品</text>
        </view>

        <!-- 菜品列表 -->
        <view v-else class="dish-list-container">
          <view v-for="(dish, index) in filteredDishList" :key="dish.id" class="dish-item">
            <view class="dish-info">
              <view class="dish-name">
                <text class="name-text">{{ dish.dish && dish.dish.name }}</text>
              </view>
              <view class="dish-category">
                <text class="category-text">{{ dish.dish && dish.dish.category }}</text>
              </view>
            </view>

            <view class="dish-price">
              <view class="price-info" v-if="role === 1">
                <text class="price-label">官方参考价格</text>
                <text class="price-value">¥{{ dish.base_price }}</text>
              </view>
              <view class="price-info" v-if="role === 1">
                <text class="price-label">供应商报价</text>
                <text class="price-value quoted">¥{{ dish.supplier_quoted_price || '-' }}</text>
              </view>
              <view class="price-info">
                <text class="price-label">实际采购价-供应商</text>
                <text class="price-value quoted">¥{{ dish.actual_price || '' }}</text>
              </view>
              <view class="price-info">
                <text class="price-label">计划采购数量-食堂</text>
                <text class="price-value">{{ dish.planned_quantity || '-' }} {{ dish.dish && dish.dish.unit }}</text>
              </view>
              <view class="price-info">
                <text class="price-label">采购备注-食堂</text>
                <text class="price-value">{{ dish.planned_remark || '-' }}</text>
              </view>
              <view class="price-info">
                <text class="price-label">实际采购数量-供应商</text>
                <text class="price-value quoted">{{ dish.actual_quantity || '' }} {{ dish.dish && dish.dish.unit }}</text>
              </view>
            </view>

          <view class="dish-price-input">
            <text class="price-label">
              验收数量
              <text style="color: red" v-if="dish.planned_quantity !== dish.actual_quantity">【数量异常】</text>
            </text>
            <view class="price-input">
              <u-number-box input-width="120" :positive-integer="false" step="1" v-model="dish.actual_quantity2"></u-number-box>
              <text class="price-unit">{{ dish.dish && dish.dish.unit }}</text>
            </view>
          </view>
            <view class="dish-quality">
              <text class="quality-label">品质评价</text>
              <view class="quality-tags">
                <view
                  v-for="(rating, index) in (dishRatingMap[`${dish.dish && dish.dish.category}-${dish.dish && dish.dish.name}`] || ['好', '中', '差'])"
                  :key="index"
                  class="quality-tag"
                  :class="{ active: dish.quality_rating === rating }"
                  @click="selectQuality(dish, rating)"
                >
                  <text class="tag-text">{{ rating }}</text>
                </view>
              </view>
            </view>

            <view class="dish-remark">
              <text class="remark-label">备注</text>
              <view class="remark-input">
                <textarea
                  v-model="dish.remark"
                  placeholder="请输入备注（选填）"
                  class="remark-field"
                  maxlength="200"
                  :show-confirm-bar="false"
                />
                <view class="char-count">
                  <text class="count-text">{{ dish.remark ? dish.remark.length : 0 }}/200</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>

      <!-- 底部统计 -->
      <view class="bottom-stats">
        <view class="stats-info">
          <text class="stats-text">总菜品数：{{ dishList.length }} 个</text>
          <text class="stats-text">已填写收货数量：{{ filledQuantityCount }} 个</text>
          <text class="stats-text">已填写品质评价：{{ filledQualityCount }} 个</text>
        </view>
        <view class="stats-total2">
            <view class="stats-total">
              <text class="total-label">实际采购总价</text>
              <text class="total-value">¥{{ totalPrice1 }}</text>
            </view>

        <view class="stats-total">
          <text class="total-label">实际验收总价</text>
          <text class="total-value">¥{{ totalPrice }}</text>
        </view>
        </view>
      </view>
    </view>
  </template>

  <script>
  import api from "../../config/api.js";

  export default {
    data() {
      return {
        workorderId: '',
        loading: true,
        searchKeyword: '',
        dishList: [],

        // 采购单信息
        workorderInfo: {},

        // 已存在的菜单项
        existingMenuItems: [],
        dishRatingMap: {}
      }
    },

    computed: {
      // 过滤后的菜品列表
      filteredDishList() {
        if (!this.searchKeyword) {
          return this.dishList;
        }
        return this.dishList.filter(dish => (dish.dish.name && dish.dish.name.includes(this.searchKeyword)) || dish.dish.category && dish.dish.category.includes(this.searchKeyword));
      },

      // 已填写收货数量的菜品数
      filledQuantityCount() {
        return this.dishList.filter(dish =>
          dish.actual_quantity2 !== null &&
          dish.actual_quantity2 !== undefined &&
          dish.actual_quantity2 > 0
        ).length;
      },

      // 已填写品质评价的菜品数
      filledQualityCount() {
        return this.dishList.filter(dish =>
          dish.quality_rating &&
          dish.quality_rating.trim() !== ''
        ).length;
      },

      // 总价
      totalPrice() {
        return this.dishList.reduce((total, dish) => {
          if (dish.actual_quantity2 && dish.actual_quantity2 > 0) {
            const price = dish.actual_price || 0
            console.log(price, dish.actual_quantity2)
            return total + (price * dish.actual_quantity2);
          }
          return total;
        }, 0).toFixed(2);
      },
      totalPrice1() {
        return this.dishList.reduce((total, dish) => {
          if (dish.actual_quantity && dish.actual_quantity > 0) {
            const price = dish.actual_price || 0
            return total + (price * dish.actual_quantity);
          }
          return total;
        }, 0).toFixed(2);
      }
    },

    onLoad(options) {
      this.$store.dispatch('getUserInfo')
      if (options.id) {
        this.workorderId = options.id;
        this.loadWorkorderInfo();
      }

      this.$api.getDishRatingList().then(res => {
        let dishRatingMap = {}
        // 将不同分类使用map形式
        res.forEach(item => {
          let key = `${item.category}-${item.dish_name}`
          if (!dishRatingMap[key]) {
            dishRatingMap[key] = item.rating_value.split(',')
          }
        })
        this.dishRatingMap = dishRatingMap
        console.log('dishRatingMap',dishRatingMap);

      })
    },

    methods: {
      // 返回上一页
      goBack() {

        uni.switchTab({
                url: '/pages/workorder/workorder'
              })
      },

      // 加载采购单信息
      loadWorkorderInfo() {
        api.getDailyMenu(this.workorderId).then(response => {
          this.workorderInfo = response;
          this.loadDishList();
        }).catch(error => {
          console.error('加载采购单信息失败:', error);
          uni.showToast({
            title: '加载失败',
            icon: 'none'
          });
        });
      },

      // 加载菜品列表
      async loadDishList() {
        this.loading = true;

        try {
          // 获取菜品列表（基于月度比价项目）
          const params = {
            daily_menu_id: this.workorderInfo.id,
          };

          const dishResponse = await api.getDailyMenuItemList(params);
          this.dishList = (dishResponse || []).map(dish => ({
            ...dish,
            actual_quantity2: dish.planned_quantity || dish.actual_quantity || 0
          }));

        } catch (error) {
          console.error('加载菜品列表失败:', error);

        } finally {
          this.loading = false;
        }
      },

      // 搜索输入
      onSearchInput() {
        // 实时搜索逻辑
      },

      // 减少数量
      decreaseQuantity(dish) {
        if (dish.actual_quantity2 > 0) {
          dish.actual_quantity2--;
        }
      },

      // 增加数量
      increaseQuantity(dish) {
        console.log(dish.actual_quantity2)
        dish.actual_quantity2 = (dish.actual_quantity2 || 0) + 1;
      },

      // 数量输入
      onQuantityInput(dish, event) {
        // console.log('dish',event);
        const value = parseInt(event.detail.value);
        if (isNaN(value) || value < 0) {
          dish.actual_quantity2 = 0;
        } else {
          dish.actual_quantity2 = value;
        }
      },

      // 选择品质评价
      selectQuality(dish, rating) {
        dish.quality_rating = rating;
      },

      save() {
        this.saveDishes(false)
      },
      submit() {

        // 验证收货数量
        const invalidDishes = this.dishList.filter(dish =>
          !dish.actual_quantity2 || dish.actual_quantity2 <= 0
        );

        if (invalidDishes.length > 0) {
          uni.showToast({
            title: '请为所有菜品设置有效的收货数量',
            icon: 'none'
          });
          return;
        }

        // 验证品质评价
        const dishesWithoutQuality = this.dishList.filter(dish =>
          !dish.quality_rating || dish.quality_rating.trim() === ''
        );

        // if (dishesWithoutQuality.length > 0) {
        //   uni.showToast({
        //     title: '请为所有菜品选择品质评价',
        //     icon: 'none'
        //   });
        //   return;
        // }
        uni.showModal({
          title: '提示',
          content: '确认提交吗？',
          success: (res) => {
            if (res.confirm) {
              this.saveDishes(true)
            }
          }
        })
      },
      // 保存菜品选择
      async saveDishes(isSubmit = false) {


        try {
          // 批量更新菜品明细
          const updateData = this.dishList.map(dish => ({
            id: dish.id,
            actual_quantity2: dish.actual_quantity2,
            quality_rating: dish.quality_rating,
            remark: dish.remark || '',
          }));

          const submitData = updateData.map(dish => ({
            daily_menu_id: this.workorderInfo.id,
            id: dish.id,
            actual_quantity2: dish.actual_quantity2,
            quality_rating: dish.quality_rating,
            remark: dish.remark || '',
            status: 3 // 已收货状态
          }));
          await api[isSubmit ? 'batchConfirmReceipt' : 'batchUpdateDailyMenuItem'](isSubmit ? submitData : updateData);


          uni.showToast({
            title: isSubmit ? '验收成功' : '保存成功',
            icon: 'success'
          });
          if (isSubmit) {
            setTimeout(() => {
              uni.navigateBack();
            }, 1000);
          }

        } catch (error) {
          console.error('确认收货失败:', error);
        }
      }
    }
  }
  </script>

  <style lang="scss">
  .dishes-container {
    background-color: #f5f5f5;
    padding-bottom: 180rpx;
    padding-top: 90rpx;
    overflow: hidden;
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  // 顶部导航
  .header {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    width: 100%;
    z-index: 2;
    background-color: #fff;
    padding: 24rpx 32rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .back-btn {
        .back-text {
          font-size: 32rpx;
          color: #666;
        }
      }

      .title {
        .title-text {
          font-size: 36rpx;
          color: #333;
          font-weight: 600;
        }
      }

      .save-btn {
        .save-text {
          font-size: 32rpx;
          color: #FFC300;
          font-weight: 500;
        }
      }
    }
  }

  // 搜索栏
  .search-section {
    background-color: #fff;
    padding: 24rpx 32rpx;
    border-bottom: 1rpx solid #f0f0f0;
    margin-bottom: 20rpx;

    .search-box {
      display: flex;
      align-items: center;
      background-color: #f8f8f8;
      border-radius: 24rpx;
      padding: 16rpx 24rpx;
      gap: 12rpx;

      .search-icon {
        width: 32rpx;
        height: 32rpx;
      }

      .search-input {
        flex: 1;
        font-size: 28rpx;
        color: #333;
      }
    }
  }


  .dish-price-input {
    margin-bottom: 24rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .price-label {
      display: block;
      font-size: 26rpx;
      color: #666;
    }

    .price-input {
      position: relative;
      display: flex;
      align-items: center;

      .price-field {
        flex: 1;
        margin-right: 60rpx;
      }

      .price-unit {
        position: absolute;
        right: 16rpx;
        font-size: 28rpx;
        color: #666;
        z-index: 1;
      }
    }
  }
  // 菜品列表
  .dish-list {
    height: 100%;
  }

  // 加载状态
  .loading-state {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 200rpx;

    .loading-text {
      font-size: 28rpx;
      color: #666;
    }
  }

  // 空状态
  .empty-state {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 400rpx;
    padding: 0 32rpx;

    .empty-icon {
      width: 200rpx;
      height: 200rpx;
      margin-bottom: 32rpx;
      opacity: 0.6;
    }

    .empty-text {
      font-size: 32rpx;
      color: #999;
      margin-bottom: 16rpx;
    }

    .empty-desc {
      font-size: 26rpx;
      color: #ccc;
    }
  }

  .dish-list-container {
    padding: 0 32rpx;
  }

  .dish-item {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 32rpx;
    margin-bottom: 24rpx;

    .dish-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24rpx;

      .dish-name {
        .name-text {
          font-size: 32rpx;
          color: #333;
          font-weight: 600;
        }
      }

      .dish-category {
        .category-text {
          font-size: 24rpx;
          color: #666;
          background-color: #e8e8e8;
          padding: 8rpx 16rpx;
          border-radius: 8rpx;
        }
      }
    }

    .dish-price {
      margin-bottom: 24rpx;

      .price-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12rpx;

        &:last-child {
          margin-bottom: 0;
        }

        .price-label {
          font-size: 26rpx;
          color: #666;
        }

        .price-value {
          font-size: 28rpx;
          color: #333;
          font-weight: 500;

          &.quoted {
            color: #FF6B35;
            font-weight: 600;
          }
        }
      }
    }

    .dish-quantity {
      display: flex;
      align-items: center;
      gap: 16rpx;

      .quantity-label {
        font-size: 26rpx;
        color: #666;
      }

      .quantity-input {
        display: flex;
        align-items: center;
        border: 1rpx solid #e8e8e8;
        border-radius: 8rpx;
        overflow: hidden;

        .quantity-btn {
          width: 60rpx;
          height: 60rpx;
          display: flex;
          justify-content: center;
          align-items: center;
          background-color: #f5f5f5;

          .btn-text {
            font-size: 32rpx;
            color: #333;
            font-weight: 600;
          }
        }

        .quantity-field {
          width: 120rpx;
          height: 60rpx;
          text-align: center;
          font-size: 28rpx;
          color: #333;
          border: none;
          background-color: #fff;
        }
      }

      .unit-text {
        font-size: 26rpx;
        color: #666;
      }
    }

    .dish-quality {
      margin-bottom: 24rpx;

      .quality-label {
        display: block;
        font-size: 26rpx;
        color: #666;
        margin-bottom: 16rpx;
      }

      .quality-tags {
        display: flex;
        gap: 16rpx;

        .quality-tag {
          padding: 12rpx 24rpx;
          border: 1rpx solid #e8e8e8;
          border-radius: 8rpx;
          background-color: #fff;

          .tag-text {
            font-size: 26rpx;
            color: #666;
          }

          &.active {
            border-color: #FFC300;
            background-color: #FFF8E1;

            .tag-text {
              color: #FFC300;
              font-weight: 500;
            }
          }
        }
      }
    }

    .dish-remark {
      .remark-label {
        display: block;
        font-size: 26rpx;
        color: #666;
        margin-bottom: 16rpx;
      }

      .remark-input {
        position: relative;

        .remark-field {
          width: 100%;
          font-size: 28rpx;
          color: #333;
          line-height: 1.5;
          height: 120rpx;
          padding: 16rpx;
          border: 1rpx solid #e8e8e8;
          border-radius: 8rpx;
          background-color: #fff;
        }

        .char-count {
          text-align: right;
          margin-top: 8rpx;

          .count-text {
            font-size: 24rpx;
            color: #999;
          }
        }
      }
    }
  }

  // 底部统计
  .bottom-stats {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    padding: 24rpx 32rpx;
    border-top: 1rpx solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .stats-info {
      display: flex;
      flex-direction: column;
      gap: 8rpx;

      .stats-text {
        font-size: 20rpx;
        color: #666;
      }
    }

    .stats-total {
      display: flex;
      align-items: center;
      gap: 12rpx;

      .total-label {
        font-size: 28rpx;
        color: #666;
      }

      .total-value {
        font-size: 36rpx;
        color: #FF6B35;
        font-weight: 600;
      }
    }
  }
  </style>
